import Vue from 'vue';
import axios from 'axios'
import config from '../config.js'
import Qs from 'qs'
import wechat from './wechat-td.js'
import layer from './layer.js'
import router from '../router/router.js' //路由模块
import md5 from 'js-md5'; //md5加密模块
import base from '../common/base.js' //基础方法
// axios.defaults.baseURL =config.api_url;

//创建一个axios实例
var axios_instance = axios.create({
    transformRequest: [function(data) {
        data = Qs.stringify(data);

        return data;
    }],
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
})
    // Vue.use(axios_instance)
//格式化数字为2位数 不足补0  返回字符串
function formatNumber(n) {
    n = n.toString()
    return n[1] ? n : '0' + n
}
//生成指定长度的随机数
function GetRandom2(n) {
    var chars = ['2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
    var res = "";
    for (var i = 0; i < n; i++) {
        var id = Math.ceil(Math.random() * 30);
        res += chars[id];
    }
    return res;
}
//60秒内不重复
function GetRandom() {
    var date = new Date();
    var expireTime = date.getTime() + 60 * 1000;
    var array = window.localStorage.getItem('apiRandomCode');
    if (array == undefined) {
        array = new Array();
    }
    //移除过保护器的数据；
    var arr = new Array();
    for (var i = 0; i < array.length; i++) {
        var item = array[i];
        if (item.expireTime > expireTime - 60 * 1000) {
            arr.push(item);
        }
    }
    var random;
    var flag = true;
    while (flag) {
        random = Math.ceil(Math.random() * 1000000);
        flag = false;
        for (var i = 0; i < arr.length; i++) {
            var value = arr[i];
            if (value.key == random) {
                flag = true;
            }
        }
    }
    var obj = new Object();
    obj.key = random;
    obj.expireTime = expireTime;
    arr.push(obj);
    window.localStorage.setItem('apiRandomCode', arr)
    return obj.key;
}
//获取时间戳
function GetTimeSpan() {
    var _date = new Date();
    var year = formatNumber(_date.getFullYear());
    var month = formatNumber(_date.getMonth() + 1);
    var day = formatNumber(_date.getDate());
    var hour = formatNumber(_date.getHours());
    var minute = formatNumber(_date.getMinutes());
    var second = formatNumber(_date.getSeconds());
    return year + month + day + hour + minute + second;
}
//错误函数处理
var OutCodeHandle={
    E800000:(_res,out_msg)=>{
        //需要重新发起用户登录
        layer.close();
        window.localStorage.removeItem('userinfo')
        router.replace('/login');
        return;
    },
    E800100:(_res,out_msg)=>{
        //需要重新发起用户登录
        layer.close();
        window.localStorage.removeItem('userinfo')
        router.replace('/login');
        return;
    },
    E404000:(_res,out_msg)=>{
        //404错误,跳转错误页
        layer.close();
        window.clearTimeout();
        router.replace('/error/e404/' + out_msg);
        return;
    },
    E401000:(_res,out_msg)=>{
        //401错误,跳转错误页
        layer.close();
        window.clearTimeout();
        router.replace('/error/e401/' + out_msg);
        return;
    },
    Error:(_res,out_msg)=>{
        //其他错误
        window.clearTimeout();
        if (_options.msg) {
            layer.msg(out_msg)
        }
        typeof _options.error === "function" && _options.error(out_msg, out_code)
        return;
    }
}

/**
 * @param {String} _options.url 请求地址
 * @param {Object} _options.data 请求数据，内层必须全为字符串
 * @param {Object} _options.headers 请求头 对象
 * @param {Function} _options.success 请求成功 
 * @param {Function} _options.error 请求错误
 * @param {Function} _options.finally 请求完成
 * @param {Boolean} _options.errormsg 是否提示错误 默认true
 */
var post = (_options) => {
        
    var headers = {
        'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
    }
    var apiClientid =base.GetFingerprint()//'webclient';
    //获取请求数据
    var data = GetData(_options)

    var requestData = {
        loading: _options.loading || '',
        url: _options.url,
        data: data,
        headers: headers,
        success: (_res) => {
            // console.log('获取结果',_res)
            var outdata = typeof _res != 'object' ? JSON.parse(_res) : _res;
            outdata = outdata.data || {};
            var out_code = outdata.out_code || '';
            var out_msg = outdata.out_msg || '未知错误';

            //这里是外层接口返回错误处理======================
            //如果不为200000 则进入错误函数处理
            if(out_code != 'E200000' || out_code=='200000' || out_code==200000) {
                if((typeof OutCodeHandle[out_code])==='function') {
                    OutCodeHandle[out_code](_res,out_msg)
                    return
                }
                OutCodeHandle.Error(_res,out_msg)
                return
            }
            
            //然后判断 是否需要进行刷新token
            if (outdata.out_refusertoken == 1 && outdata.out_usertoken.length > 0) {
                window.localStorage.setItem('usertoken', outdata.out_usertoken);
                window.localStorage.setItem('userid', outdata.out_userid);
            }
            //当out_code==E200000后  处理内层===========================
            var data = JSON.parse(outdata.out_bodydata);
            if (!data) {
                typeof _options.error === "function" && _options.error('未知错误', 0)
                return;
            }
            var status = outdata.out_status || 0;
            var msg = outdata.out_msg || '未知错误'
            if (status == 101) {
                window.location.href = '/'
                return;
            }
            if (status != 1) {
                if (_options.msg) {
                    layer.msg(msg, {
                        end: () => {
                            typeof _options.error === "function" && _options.error(msg, 0)
                        }
                    })
                } else {
                    typeof _options.error === "function" && _options.error(msg, 0)
                }
                return;
            }
            if (_options.smsg) {
                layer.msg(msg, {
                    end: () => {
                        typeof _options.success === "function" && _options.success(data, msg, status);
                    }
                })
            } else {
                typeof _options.success === "function" && _options.success(data, msg, status);
            }


            return;
        },
        error: (_msg) => {
            if (_options.msg) {
                layer.msg('请求异常'+_msg)
            }
            typeof _options.error === "function" && _options.error('请求异常');
        },
        finally: () => {
            typeof _options.finally === "function" && _options.finally();
        }
    }
    //进行请求
    axiosRequest(requestData);
}
    //============================================以下为处理返回数据方法 无需改动


//============================================以下为请求 无需改动
//签名请求数据
function SignData(_data, _clientid) {
    var data = {};
    data.in_appid = config.appid;//数据主体
    data.in_bodydata = JSON.stringify(_data);//数据主体
    data.in_clientid = _clientid || '';//clientid
    data.in_random = GetRandom()//随机数
    data.in_timestamp = GetTimeSpan();//时间戳
    
    //签名组件请联系程序员
    return _data;
    
}
function GetData(_options){

    var data = _options.data || {}
    var finger=base.GetFingerprint();//以浏览器指纹作为唯一标识 只有同一台电脑同一个浏览器才会唯一
    data = SignData(data,finger)

    //==========================以下参数不进行签名
    data.device_info=JSON.stringify({title:'web',id:finger,info:''});
    data.in_source = '4';//请求来源
    data.usertoken = window.localStorage.getItem('usertoken') || ''

    return data;
    
    
}
//执行一次axios请求
var axiosRequest = (_reqData) => {

    if(_reqData.loading && _reqData.loading==true) {
        _reqData.loading='载入中'
    } else {
        _reqData.loading=_reqData.loading || '';
    }

    if (_reqData.loading.length > 0) {
        layer.loading(_reqData.loading)
    }
    
    axios({
        url: config.api_url + _reqData.url,
        data: _reqData.data,
        headers: _reqData.headers,
        withCredentials: false,
        method: 'post',
    }).then(function(_res) {
        if (_reqData.loading.length > 0) {
            layer.close()
        }
        typeof _reqData.success === "function" && _reqData.success(_res);
    }).catch(function(_res) {
        if (_reqData.loading.length > 0) {
            layer.close()
        }
        typeof _reqData.error === "function" && _reqData.error(_res);
    }).finally((_res) => {
        typeof _reqData.finally === "function" && _reqData.finally(_res);
    })
}
var axiosRequestHttp = (_reqData) => {
    axios({
        url: _reqData.url,
        data: _reqData.data,
        headers: _reqData.headers,
        contentType: false,
        processData: false,
        method: 'post',
    }).then(function(_res) {
        typeof _reqData.success === "function" && _reqData.success(_res);
    }).catch(function(_res) {
        typeof _reqData.error === "function" && _reqData.error(_res);
    }).finally((_res) => {
        typeof _reqData.finally === "function" && _reqData.finally(_res);
    })
}
export default {
    post: post,
    onpost: axiosRequestHttp
}


